package com.go.where.manager.dao.impl;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.go.where.manager.dao.BaseDao;
import com.go.where.manager.page.BaseQuery;
import com.go.where.manager.page.Pagination;

/**
 * 基础数据库操作的实现类
 * 
 * @author
 * 
 * @param <T>
 */
public abstract class BaseDaoImpl<T> extends SqlSessionDaoSupport implements
		BaseDao<T> {

	/**
	 * 命名空间
	 * 
	 * @return
	 */
	protected abstract String getNameSpace();

	@Override
	public int insert(T obj) {
		return getSqlSession().insert(getNameSpace() + ".insert", obj);
	}

	@Override
	public void batchInsert(List<T> objects) {
		for (T obj : objects) {
			setPrimary(getNextKey(), obj);
		}
		getSqlSession().insert(getNameSpace() + ".batchInsert", objects);
	}

	/**
	 * 设置主键值
	 * 
	 * @param nextKey
	 * @param obj
	 */
	protected void setPrimary(String nextKey, T obj) {

	}

	@Override
	public String getNextKey() {
		return getSqlSession().selectOne(getNameSpace() + ".getNextKey");
	}

	@Override
	public int update(T obj) {
		return getSqlSession().update(getNameSpace() + ".update", obj);
	}

	@Override
	public int deleteByKey(String id) {
		return getSqlSession().delete(getNameSpace() + ".deleteByKey", id);
	}

	@Override
	public T getByKey(String id) {
		return getSqlSession().selectOne(getNameSpace() + ".selectByKey", id);
	}

	/**
	 * 根据记录总数，分页查询相关计算
	 * 
	 * @param rowCount
	 *            符合条件的记录总数
	 * @param list
	 *            记录结果集list
	 * @param query
	 *            当前页和每页显示记录个数对象
	 * @return
	 */
	public Pagination<T> queryPagination(Integer rowCount, List<T> list,
			BaseQuery query) {
		Integer curIndex = query.getCurrentPage();
		Pagination<T> page = new Pagination<T>(curIndex, rowCount, query
				.getPageSize(), list);

		return page;
	}

	@Override
	public int totalCount(BaseQuery query) {
		return getSqlSession().selectOne(getNameSpace() + ".queryCount", query);
	}

	@Override
	public List<T> queryList(BaseQuery query) {
		return getSqlSession().selectList(getNameSpace() + ".queryList", query);
	}

}
